package grammar.parser;

import error.processing.MyErrorProcessing;
import execution.Executable;
import grammar.parser.stmt.Block;
import grammar.parser.stmt.ReturnStmt;
import semantic.parser.SymbolTableElement;
import word.parser.WordElement;

import java.util.List;

public class MainFuncDef extends GrammarParser implements Executable {
    private final Block block;

    public MainFuncDef(Block block) {
        this.block = block;
    }

    public static MainFuncDef buildMainFunc() {
        assert getAnalyzingWord().getType() == WordElement.WordType.INTTK;
        analyzeNextWord();
        MyErrorProcessing.haveReturn();
        assert getAnalyzingWord().getType() == WordElement.WordType.MAINTK;
        analyzeNextWord();
        assert getAnalyzingWord().getType() == WordElement.WordType.LPARENT;
        analyzeNextWord();
        assert getAnalyzingWord().getType() == WordElement.WordType.RPARENT;
        analyzeNextWord();
        Block block = Block.buildBlock();

        MainFuncDef mainFunc = new MainFuncDef(block);
        mainFunc.returnCheck();
        return mainFunc;
    }

    public void returnCheck() {

        List<BlockItem> blockItemList = block.getBlockItemList();

        if (blockItemList.size() < 1 ||
                !(blockItemList.get(blockItemList.size() - 1) instanceof ReturnStmt)) {
            MyErrorProcessing.buildErrorProcessing(MyErrorProcessing.ErrorType.g,
                    getAnalyzingWord(-1));
        }
    }

    @Override
    public void execute() {
        block.execute();
    }
}
